package com.ebai.product.management.repository.system;

import java.util.List;

import javax.persistence.Table;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.ebai.product.management.base.utils.SysCode;
import com.ebai.product.management.model.entity.Role;

@Repository
@Table(name="role")
@Qualifier("roleRepository")
public interface RoleRepository extends CrudRepository<Role, String>, JpaSpecificationExecutor<Role> {

    public Role save(Role role);

    public void deleteByPid(String pid);

    public void delete(Role entity);

    public Role findByPid(String pid);

    public List<Role> findAll();
    
    Page<Role> findAll(Specification<Role> specification, Pageable pageable);
    
    @Query("select t from Role t where t.roleName=:roleName and t.isDelete='"+SysCode.DICT_TYSF.NO+"' ")
    public Role findRoleByRoleName(@Param("roleName") String roleName);

    @Query("select t from Role t where t.roleName=:roleName and t.isDelete='"+SysCode.DICT_TYSF.NO+"' and t.roleType!='"+SysCode.DEFAULT_USER.SADMIN_ROLE+"' ")
    public List<Role> queryRoleListByRoleName(@Param("roleName") String roleName);
    
    @Query(nativeQuery = true,value = "select r.pid, r.role_name, r.role_type, r.role_describe from t_global_user u "
    		+ "left join t_global_role_user ur on u.pid = ur.user_pid "
    		+ "left join t_global_role r on ur.role_pid = r.pid where ur.user_pid = :userPid ")
    public List<Object> selectRolesByUserId(@Param("userPid") String userPid);
    
    @Query(nativeQuery = true,value = "select a.pid,a.role_type,a.role_name,a.role_describe,b.user_pid "
    		+ "from t_global_role a left join t_global_role_user b on a.pid = b.role_pid and b.user_pid=:userPid "
    		+ "where a.is_delete='"+SysCode.DICT_TYSF.NO+"' and a.role_type!='"+SysCode.DEFAULT_USER.SADMIN_ROLE+"' order by a.create_time")
    public List<Object> selectRoleByUserId(@Param("userPid") String userPid);
    
    @Query("select t from Role t where t.isDelete='"+SysCode.DICT_TYSF.NO+"' and t.roleType!='"+SysCode.DEFAULT_USER.SADMIN_ROLE+"' ")
    public List<Role> findRolesAll();
}
